package com.wen.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wen.common.pojo.system.Permission;
import com.wen.common.utils.ResponseResult;
import com.wen.system.mapper.PermissionMapper;
import com.wen.system.mapper.RoleMapper;
import com.wen.system.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;

@Service
public class PermissionSvcImpl implements PermissionService {


    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public List<Permission> getAllPermission() {
        return permissionMapper.selectList(null);
    }

    @Override
    public Page<Permission> findPermissionPage(int pageNum, int pageSize, String search) {
        LambdaQueryWrapper<Permission> wrapper = Wrappers.lambdaQuery();
        if (StrUtil.isNotBlank(search)) {
            wrapper.like(Permission::getMenuName, search);
        }
        Page<Permission> permissionPage = permissionMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);

        return permissionPage;
    }

    @Override
    public int add(Permission permission) {
        permission.setCreateTime(new Date());
        int insert = permissionMapper.insert(permission);
        return insert;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id) {
        int i = permissionMapper.deleteById(id);
        // 更新rolePermission
        roleMapper.delRolePermissionByPermId(id);
        return i;
    }

    @Override
    public int update(Permission permission) {
        permission.setModifiedTime(new Date());
        int i = permissionMapper.updateById(permission);
        return i;
    }

    @Override
    public Permission getMenuById(Long menuId) {
        return permissionMapper.selectById(menuId);
    }

    @Override
    public ResponseResult<?> selectMenuList(Permission permission) {
        List<Permission> list = permissionMapper.selectMenuList(permission);
        List<Permission> menuTree = this.getMenuTree(list, 0);
        return ResponseResult.success(menuTree);
    }

    /*
     * 菜单树思路：
     * 1.根据一个菜单找出子菜单 （有无子菜单）
     * 2. 有的话，递归子菜单
     * */

    /**
     * 构建前端所需要树结构
     *
     * @param menuList 菜单列表
     * @param rootId   根菜单id
     * @return 树结构的菜单列表
     */
    @Override
    public List<Permission> getMenuTree(List<Permission> menuList, int rootId) {

        List<Permission> menuTree = new ArrayList<>();
        // 遍历集合 迭代器效率更高点
        for (ListIterator<Permission> iterator = menuList.listIterator(); iterator.hasNext(); ) {
            Permission permission = iterator.next();
            // 找出形参菜单中的根菜单 ：parentId为0的
            if (permission != null && permission.getParentId() != null && permission.getParentId() == rootId) {
                // 递归操作，递归子菜单
                recursionFn(menuList, permission);

                menuTree.add(permission);

            }
//            else { // parentId不为0的（下级菜单）
//
//                List<Permission> allPermission = this.getAllPermission();
//                // 找这个菜单在所有菜单中的的父菜单
//                Permission parent = this.getParent(allPermission, permission);
//                //判断menuList中有没有这个元素，       /*（适配添加菜单的父级菜单）*/
//                if (!menuList.contains(parent)) {
//                    iterator.add(parent);
//                    // 设置上一 索引
//                    Permission item = iterator.previous();
//                }
//            }
        }
        if (menuTree.isEmpty()) {
            menuTree = menuList;
        }
        return menuTree;
    }

    /**
     * 递归子节点
     */
    protected void recursionFn(List<Permission> menuList, Permission t) {
        // 获取子菜单
        List<Permission> childList = getChildList(menuList, t);
        t.setChildren(childList);
        // 子菜单的子节点
        for (Permission tChild : childList) {
            // 递归条件 判断是否有子菜单
            if (hasChild(menuList, tChild)) {
                recursionFn(menuList, tChild);
            }
        }
    }

    /**
     * 根据一个菜单找出它的子菜单
     */
    protected List<Permission> getChildList(List<Permission> menuList, Permission t) {
        //子菜单
        List<Permission> childList = new ArrayList<>();

        for (Permission permission : menuList) {
            if (permission.getParentId() != null && permission.getParentId().equals(t.getId())) {
                childList.add(permission);
            }
        }
        return childList;
    }

    /**
     * 判断一个菜单有没有子菜单
     */
    protected boolean hasChild(List<Permission> list, Permission t) {
        return !getChildList(list, t).isEmpty();
    }


    /**
     * 找菜单的父菜单
     */
    public Permission getParent(List<Permission> menus, Permission t) {
        Permission permission = null;
        for (Permission menu : menus) {
            if (t.getParentId() != null && t.getParentId() == menu.getId()) { // 返回的菜单项应该有问题，明天看
                permission = menu;
            }
        }
        return permission;
    }

}